<template>
  <div style="display: flex; gap: 20px; padding: 20px;">
    <!-- 左侧表单 -->
    <div style="flex: 1;">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        style="max-width: 600px;"
      >
        <!-- 基础信息 -->
        <h3>基础信息</h3>

        <el-form-item label="工艺流程编号" prop="flowCode">
          <div style="display: flex; justify-content: center;">
            <el-input v-model="ruleForm.flowCode" :disabled="autoGenerate" />
            <el-checkbox v-model="autoGenerate" style="margin-left: 10px;">系统编号</el-checkbox>
          </div>
        </el-form-item>

        <el-form-item label="工艺流程名称" prop="flowName">
          <el-input v-model="ruleForm.flowName" />
        </el-form-item>

        <el-form-item label="负责人" prop="personId">
          <el-select v-model="ruleForm.personId" placeholder="请选择负责人">
            <el-option
              v-for="item in accountNames"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="ruleForm.departmentId" placeholder="请选择部门">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.departmentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="ruleForm.isActive">
            <el-radio value="true">启用</el-radio>
            <el-radio value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input v-model="ruleForm.remarks" type="textarea" />
        </el-form-item>

        <!-- 加工工序 -->
<h3>加工工序</h3>
<div style="display: flex; gap: 10px; margin-bottom: 10px;">
  <el-button type="primary" size="small" @click="showAddStepDialog = true">添加</el-button>
  <el-button type="danger" size="small" @click="removeSelectedSteps()">移除</el-button>
</div>

<el-table
  :data="processSteps"
  style="width: 1300px; min-width: 1300px; overflow-x: auto;"
  border
  @selection-change="handleSelectionChange"
>
  <!-- 列定义保持不变 -->
</el-table>

        <el-table
  :data="processSteps"
  style="width: 1300px; min-width: 1300px; overflow-x: auto;"
  border
  @selection-change="handleSelectionChange"
>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" width="80">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="加工工序" min-width="120">
            <template #default="{ row }">
              {{ row.processCode }}
            </template>
          </el-table-column>
          <el-table-column label="工序编码" min-width="150">
            <template #default="{ row }">
              {{ row.processCode }}
            </template>
          </el-table-column>
          <el-table-column label="工序名称" min-width="200">
            <template #default="{ row }">
              {{ row.processName }}
            </template>
          </el-table-column>
          <el-table-column label="负责人" min-width="120">
            <template #default="{ row }">
              {{ row.personName }}
            </template>
          </el-table-column>
          <el-table-column label="所属部门" min-width="150">
            <template #default="{ row }">
              {{ row.departmentName }}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template #default="{ row }">
              <el-input v-model="row.remarks" size="small" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="240" fixed="right">
            <template #default="{ $index }">
              <el-button size="small" @click="moveUp($index)">上移</el-button>
              <el-button size="small" @click="moveDown($index)">下移</el-button>
              <el-button size="small" type="danger" @click="removeStep($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 20px;">
          <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </div>
      </el-form>
    </div>

    <!-- 右侧添加工序弹窗 -->
    <div style="width: 1000px;">
      <el-dialog title="添加工序" v-model="showAddStepDialog" width="1000px">
        <el-table :data="availableSteps" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" width="60">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="工序编码" min-width="120">
            <template #default="{ row }">
              {{ row.processCode }}
            </template>
          </el-table-column>
          <el-table-column label="工序名称" min-width="150">
            <template #default="{ row }">
              {{ row.processName }}
            </template>
          </el-table-column>
          <el-table-column label="负责人" min-width="120">
            <template #default="{ row }">
              {{ row.personName }}
            </template>
          </el-table-column>
          <el-table-column label="所属部门" min-width="150">
            <template #default="{ row }">
              {{ row.departmentName }}
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px; text-align: right;">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalSteps"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAddStepDialog = false">取消</el-button>
            <el-button type="primary" @click="addSelectedSteps">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import router from '@/router';

// ==================== 接口返回数据类型定义 ====================
interface ProcessStep {
  id: number;
  processCode: string;
  processName: string;
  categoryId: number;
  categoryName: string;
  personId: number;
  personName: string;
  departmentId: number;
  departmentName: string;
  isActive: boolean;
  remarks: string;
}

interface ProcessResponse {
  totalcount: number;
  totalPage: ProcessStep[];
}

interface Account {
  id: number;
  realName: string;
}

interface Department {
  id: number;
  departmentName: string;
}

// ==================== 表单数据 ====================
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  flowCode: '',
  flowName: '',
  personId: null as number | null,
  departmentId: null as number | null,
  isActive: 'true',
  remarks: ''
})

// 自动生成编号
const autoGenerate = ref(false)
watch(autoGenerate, (val) => {
  if (val) {
    ruleForm.flowCode = `SCDH${Date.now()}${Math.floor(Math.random() * 10000)}`
  } else {
    ruleForm.flowCode = ''
  }
})

// 负责人数据源
//负责人数据源
const accountNames=ref([{
    id:null,
    realName:''
}])
// 获取负责人数据
const fetchPersons = () => {
  axios.get('/api/Accounts/ClientGet')
    .then(res => {
      accountNames.value = res.data.totalPage;
    });
};
// 部门列表
const departments = ref<Department[]>([])
const fetchDepartments = () => {
  axios.get('/api/Accounts/GetDepartments')
    .then(res => {
      departments.value = res.data.data || []
    })
    .catch(err => console.error('获取部门失败:', err))
}

// 加工工序列表（已选）
const processSteps = ref<ProcessStep[]>([])

// 添加工序弹窗
const showAddStepDialog = ref(false)

// 可用工序列表
const availableSteps = ref<ProcessStep[]>([])
const totalSteps = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

const fetchAvailableSteps = () => {
  axios.get<ProcessResponse>(`/api/ProcessManagement/GetProcessManagements`, {
    params: {
      page: currentPage.value,
      size: pageSize.value
    }
  })
    .then(res => {
      availableSteps.value = res.data.totalPage || []
      totalSteps.value = res.data.totalcount
    })
    .catch(err => console.error('获取工序失败:', err))
}

// 事件处理
const selectedStepIds = ref<number[]>([])

const handleSelectionChange = (selection: ProcessStep[]) => {
  selectedStepIds.value = selection.map(s => s.id)
}

const addSelectedSteps = () => {
  const newSteps = availableSteps.value.filter(step => selectedStepIds.value.includes(step.id))
  processSteps.value.push(...newSteps)
  showAddStepDialog.value = false
  selectedStepIds.value = []
}

const removeStep = (index: number) => {
  processSteps.value.splice(index, 1)
}

const moveUp = (index: number) => {
  if (index > 0) {
    const temp = processSteps.value[index]
    processSteps.value[index] = processSteps.value[index - 1]
    processSteps.value[index - 1] = temp
  }
}

const moveDown = (index: number) => {
  if (index < processSteps.value.length - 1) {
    const temp = processSteps.value[index]
    processSteps.value[index] = processSteps.value[index + 1]
    processSteps.value[index + 1] = temp
  }
}

const removeSelectedSteps = () => {
  processSteps.value = processSteps.value.filter(step => !selectedStepIds.value.includes(step.id))
  selectedStepIds.value = []
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchAvailableSteps()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchAvailableSteps()
}

// 表单验证规则
const rules = reactive<FormRules>({
  flowCode: [
    { required: true, message: '请输入工艺流程编号', trigger: 'blur' }
  ],
  flowName: [
    { required: true, message: '请输入工艺流程名称', trigger: 'blur' }
  ],
  personId: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ]
})

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const payload = {
        flowCode: ruleForm.flowCode,
        flowName: ruleForm.flowName,
        personId: ruleForm.personId,
        departmentId: ruleForm.departmentId,
        isActive: ruleForm.isActive === 'true',
        remarks: ruleForm.remarks,
        procedures: processSteps.value.map(step => ({
          processCode: step.processCode,
          processName: step.processName,
          personId: step.personId,
          departmentId: step.departmentId,
          remarks: step.remarks
        }))
      }

      axios.post('/api/ProcessFlow/AddProcessFlows', payload)
        .then(() => {
          ElMessage.success('创建成功')
          router.push({ path: "/ProcessFlow" })
          resetForm(formEl)
          processSteps.value = []
        })
        .catch(err => {
          if (err.response?.status === 404) {
            ElMessage.error('接口不存在，请检查后端服务或路径')
          } else if (err.response?.status === 400) {
            ElMessage.error('请求参数错误，请检查数据格式')
          } else {
            ElMessage.error('创建失败，请联系管理员')
          }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  router.push({ path: "/ProcessFlow" })
}

// 页面挂载时初始化
onMounted(() => {
  fetchPersons()
  fetchDepartments()
  fetchAvailableSteps()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>